import { TaskManager } from '../../utils/taskManager.js'

Page({
  data: {
    loading: false,
    reportData: {
      basic: {
        totalTasks: 0,
        completedTasks: 0,
        pendingTasks: 0,
        completionRate: 0
      },
      timeRange: {
        today: { created: 0 },
        week: { created: 0, completed: 0 },
        month: { created: 0, completed: 0 }
      },
      priority: {
        high: 0,
        medium: 0,
        low: 0
      },
      performance: {
        avgCompletionTime: 0,
        weeklyAverage: 0,
        monthlyAverage: 0
      }
    },
    chartData: {
      completionTrend: [], // 完成趋势数据
      priorityDistribution: [], // 优先级分布
      timeDistribution: [] // 时间分布
    },
    selectedTimeRange: 'week', // 选中的时间范围：week, month, all
    showDetailedStats: false // 是否显示详细统计
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('数据分析页面加载')
    this.loadAnalyticsData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadAnalyticsData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadAnalyticsData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 加载分析数据
   */
  loadAnalyticsData() {
    this.setData({ loading: true })
    
    try {
      const reportResult = TaskManager.getAnalyticsReport()
      
      if (reportResult.success) {
        const reportData = reportResult.data
        
        // 生成图表数据
        const chartData = this.generateChartData(reportData)
        
        this.setData({
          reportData: reportData,
          chartData: chartData,
          loading: false
        })
        
        console.log('分析数据加载成功:', reportData)
      } else {
        throw new Error(reportResult.message)
      }
    } catch (error) {
      console.error('加载分析数据失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  /**
   * 生成图表数据
   */
  generateChartData(reportData) {
    // 优先级分布数据
    const priorityDistribution = [
      {
        name: '高优先级',
        value: reportData.priority.high,
        color: '#ff4757',
        percentage: this.calculatePercentage(reportData.priority.high, reportData.basic.totalTasks)
      },
      {
        name: '中优先级',
        value: reportData.priority.medium,
        color: '#ffa502',
        percentage: this.calculatePercentage(reportData.priority.medium, reportData.basic.totalTasks)
      },
      {
        name: '低优先级',
        value: reportData.priority.low,
        color: '#2ed573',
        percentage: this.calculatePercentage(reportData.priority.low, reportData.basic.totalTasks)
      }
    ]

    // 完成趋势数据（模拟最近7天的数据）
    const completionTrend = this.generateCompletionTrend()

    // 时间分布数据
    const timeDistribution = [
      {
        name: '今日',
        created: reportData.timeRange.today.created,
        completed: 0 // 今日完成数据需要单独计算
      },
      {
        name: '本周',
        created: reportData.timeRange.week.created,
        completed: reportData.timeRange.week.completed
      },
      {
        name: '本月',
        created: reportData.timeRange.month.created,
        completed: reportData.timeRange.month.completed
      }
    ]

    return {
      priorityDistribution,
      completionTrend,
      timeDistribution
    }
  },

  /**
   * 计算百分比
   */
  calculatePercentage(value, total) {
    return total > 0 ? Math.round((value / total) * 100) : 0
  },

  /**
   * 生成完成趋势数据（最近7天）
   */
  generateCompletionTrend() {
    const tasks = TaskManager.getAllTasks()
    const trend = []
    const now = Date.now()
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(now - i * 24 * 60 * 60 * 1000)
      const dayStart = new Date(date.setHours(0, 0, 0, 0)).getTime()
      const dayEnd = new Date(date.setHours(23, 59, 59, 999)).getTime()
      
      const dayCreated = tasks.filter(task => 
        task.createTime >= dayStart && task.createTime <= dayEnd
      ).length
      
      const dayCompleted = tasks.filter(task => 
        task.status === 1 && task.completeTime >= dayStart && task.completeTime <= dayEnd
      ).length
      
      trend.push({
        date: this.formatDate(dayStart),
        created: dayCreated,
        completed: dayCompleted
      })
    }
    
    return trend
  },

  /**
   * 格式化日期
   */
  formatDate(timestamp) {
    const date = new Date(timestamp)
    return (date.getMonth() + 1) + '/' + date.getDate()
  },

  /**
   * 切换时间范围
   */
  onTimeRangeChange(e) {
    const timeRange = e.currentTarget.dataset.range
    this.setData({ selectedTimeRange: timeRange })
    
    // 重新生成对应时间范围的数据
    this.updateTimeRangeData(timeRange)
  },

  /**
   * 更新时间范围数据
   */
  updateTimeRangeData(timeRange) {
    // 这里可以根据选择的时间范围重新计算数据
    const rangeMap = {
      week: '本周',
      month: '本月',
      all: '全部'
    }
    
    wx.showToast({
      title: `切换到${rangeMap[timeRange]}数据`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 切换详细统计显示
   */
  toggleDetailedStats() {
    this.setData({
      showDetailedStats: !this.data.showDetailedStats
    })
  },

  /**
   * 导出分析报告
   */
  exportReport() {
    try {
      const reportData = this.data.reportData
      const exportData = {
        title: 'TodoList 数据分析报告',
        generateTime: new Date().toISOString(),
        summary: {
          totalTasks: reportData.basic.totalTasks,
          completionRate: reportData.basic.completionRate + '%',
          avgCompletionTime: reportData.performance.avgCompletionTime + '小时',
          weeklyAverage: reportData.performance.weeklyAverage + '个/天'
        },
        details: reportData
      }
      
      wx.showModal({
        title: '导出分析报告',
        content: `报告包含 ${reportData.basic.totalTasks} 个任务的详细分析数据`,
        showCancel: true,
        confirmText: '确定导出',
        success: (res) => {
          if (res.confirm) {
            wx.showToast({
              title: '报告导出成功',
              icon: 'success'
            })
          }
        }
      })
    } catch (error) {
      console.error('导出报告失败:', error)
      wx.showToast({
        title: '导出失败',
        icon: 'error'
      })
    }
  },

  /**
   * 分享分析报告
   */
  shareReport() {
    const { basic, performance } = this.data.reportData
    
    const shareText = `我的TodoList数据报告：
📊 总任务数：${basic.totalTasks}
✅ 完成率：${basic.completionRate}%
⏱️ 平均完成时间：${performance.avgCompletionTime}小时
📈 每周平均：${performance.weeklyAverage}个任务

继续加油，高效管理每一天！`

    wx.showShareMenu({
      withShareTicket: true
    })

    wx.showModal({
      title: '分享数据报告',
      content: shareText,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 查看任务建议
   */
  viewSuggestions() {
    const { basic, performance, priority } = this.data.reportData
    let suggestions = []
    
    // 根据数据生成建议
    if (basic.completionRate < 60) {
      suggestions.push('💡 完成率偏低，建议优化任务规划')
    }
    
    if (performance.avgCompletionTime > 72) {
      suggestions.push('⏰ 任务完成时间较长，可以尝试分解大任务')
    }
    
    if (priority.high > priority.medium + priority.low) {
      suggestions.push('🎯 高优先级任务较多，注意合理安排时间')
    }
    
    if (basic.pendingTasks > basic.completedTasks * 2) {
      suggestions.push('📝 待办任务积压较多，建议及时处理')
    }
    
    if (suggestions.length === 0) {
      suggestions.push('🎉 数据表现良好，继续保持!')
    }
    
    wx.showModal({
      title: '智能建议',
      content: suggestions.join('\n\n'),
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 重置统计数据
   */
  resetStats() {
    wx.showModal({
      title: '重置统计',
      content: '确定要重置所有统计数据吗？这将清空历史记录！',
      confirmText: '重置',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showModal({
            title: '功能开发中',
            content: '统计数据重置功能正在开发中，敬请期待',
            showCancel: false
          })
        }
      }
    })
  }
}) 